/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.sharding.client.strategy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lvyh.lightframe.sharding.client.common.DataTableInfo;
import com.mzlion.easyokhttp.HttpClient;
import com.mzlion.easyokhttp.response.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AdaptiveShardingStrategy implements ShardingStrategy {
    private final static Logger logger = LoggerFactory.getLogger(AdaptiveShardingStrategy.class);

    private String adminUrl;

    public AdaptiveShardingStrategy(String adminUrl) {
        this.adminUrl = adminUrl;
    }

    private String getShardInfo(long shardValue) {
        String url = adminUrl + "/" + shardValue;
        HttpResponse responseData = HttpClient
                .get(url)
                .execute();

        if (responseData.isSuccess()) {
            return responseData.asString();
        }
        return "";
    }


    @Override
    public DataTableInfo doShard(String logicDsKey, String logicTableName, Object shardingValue, int tableShardNum, int dbShardNum) {
        DataTableInfo dataTableInfo = new DataTableInfo();

        // Adaptive database and table scene
        long shardValue = Long.valueOf(shardingValue.toString());

        String shardInfo = getShardInfo(shardValue);
        logger.info("[AdaptiveShardingStrategy] print adaptive shard info:{}", shardInfo);

        JSONObject jsonObject = JSON.parseObject(shardInfo);
        String tableName = jsonObject.getString("tableName");
        String dsKey = jsonObject.getString("dsKey");
        dataTableInfo.setPhysicalTableName(tableName);
        dataTableInfo.setPhysicalDataSourceKey(dsKey);

        return dataTableInfo;
    }

}
